//
//  PicNewsInfoModel.m
//  govern
//  图片新闻
//  Created by freedom on 14-8-21.
//  Copyright (c) 2014年 LiangLigeng. All rights reserved.
//

#import "PicNewsInfoModel.h"
#import "FMDatabase.h"
#import "FMResultSet.h"

@implementation PicNewsInfoModel
@synthesize cotentID,title,imageUrl,createdate;

-(NSDictionary *) toDictionary
{
    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:@"contentID",@"contentID",@"title",@"title",@"imageUrl",@"imageUrl",@"PublishDate",@"createdate", nil];
    return dic;
}

+(PicNewsInfoModel *) picNewsFromDictionary:(NSDictionary *)dic
{
    PicNewsInfoModel *model=[[PicNewsInfoModel alloc] init];
    [model setCotentID:[dic objectForKey:@"ContentID"]];
    [model  setTitle:[dic objectForKey:@"Title"]];
    [model setImageUrl:[dic objectForKey:@"imgurl"]];
    [model setCreatedate:[dic objectForKey:@"PublishDate"]];
    return model;
}

+(BOOL)checkTableCreateInDb:(FMDatabase *)db
{
    NSString *sql=@"CREATE  TABLE  IF NOT EXISTS picnewsinfo ('ID' text,'cotentID' text,'title' text,'imageUrl' text,'type' text,'createdate' text)";
    BOOL worked=[db executeUpdate:sql];
    
    return worked;
}

+(BOOL) savePicNews:(PicNewsInfoModel *)model
{
    FMDatabase *db=[[FMDatabase alloc] init];
    
    if (![db open]) {
        NSLog(@"打开数据库失败");
        return NO;
    }
    
    [PicNewsInfoModel checkTableCreateInDb:db];
    
    NSString *sql=@"insert or replace into picnewsinfo ('cotentID','title','imageUrl','createdate') values(?,?,?,?)";
    BOOL worked=[db executeUpdate:sql,model.cotentID,model.title,model.imageUrl,model.createdate];
    [db close];
    
    return worked;
}

+(BOOL) deleteAllPicNews
{
    FMDatabase *db=[[FMDatabase alloc] init];
    
    if (![db open]) {
        NSLog(@"打开数据库失败");
        return NO;
    }
    
    [PicNewsInfoModel checkTableCreateInDb:db];
    
    NSString *sql=@"delete picnewsinfo";
    BOOL worked=[db executeUpdate:sql];
    [db close];
    
    return worked;
}

+(NSMutableArray *) getAllPicNews
{
    FMDatabase *db=[[FMDatabase alloc]   init];
    
    if (![db open]) {
        NSLog(@"打开数据库失败");
        return NO;
    }
    
    [PicNewsInfoModel checkTableCreateInDb:db];
    
    NSMutableArray *arr=[[NSMutableArray alloc] init];
    
    NSString *sql=@"select * from picnewsinfo";
    FMResultSet *result=[db executeQuery:sql];
    PicNewsInfoModel *model;
    while ([result next]) {
        model=[[PicNewsInfoModel alloc] init];
        //model.ID=[result stringForColumn:@"ID"];
        model.cotentID=[result stringForColumn:@"contentID"];
        model.title=[result stringForColumn:@"title"];
        model.imageUrl=[result stringForColumn:@"imageUrl"];
        //model.type=[result stringForColumn:@"type"];
        model.createdate=[result stringForColumn:@"createdate"];
        [arr addObject:model];
    }
    [db close];
    
    return arr;
}

@end
